package com.maxmlr.nio.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName NIOEchoClientHandler
 * @Description TODO
 * @Author maxiao
 * @Date 2020/4/21 上午10:13
 * @Version V1.0
 */
public class NIOEchoClientHandler implements Runnable {

    private String address;
    private int port;

    private Selector selector;
    private SocketChannel socketChannel;

    private ExecutorService executorService;

    private volatile boolean stop;

    public NIOEchoClientHandler(String address, int port) {
        this.address = address;
        this.port = port;
        executorService = Executors.newSingleThreadExecutor();

        init();
    }

    private void init() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        try {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            socketChannel.connect(new InetSocketAddress(address, port));
        } catch (Exception e) {
            e.printStackTrace();
        }

        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    handleInput(selectionKey);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }


    }

    private void handleInput(SelectionKey key) throws IOException {
        if (!key.isValid()) {
            return;
        }
        SocketChannel channel = (SocketChannel) key.channel();
        //判断是否是可用的连
        if (key.isConnectable()) {
            if (channel.finishConnect()) {
                System.out.println("连接服务器。。。。");
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                System.out.println("请输入消息：");

                executorService.submit(()->{
                    while (true){
                        try {
                            buffer.clear();

                            InputStreamReader isr = new InputStreamReader(System.in);
                            BufferedReader br = new BufferedReader(isr);

                            String msg = br.readLine();

                            buffer.put(msg.getBytes());
                            buffer.flip();

                            channel.write(buffer);
                            System.out.println("请输入消息：");

                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });

                //注册读事件
                channel.register(selector,SelectionKey.OP_READ);

            }


        }
        if (key.isReadable()) {

            ByteBuffer buffer =  ByteBuffer.allocate(1024);
            int read = channel.read(buffer);
            if (read>0){
                buffer.flip();
                byte[] bytes=new byte[buffer.remaining()];
                buffer.get(bytes);
                String str = new String(bytes,"utf-8");

                System.out.println(str);



            }


        } else if (key.isAcceptable()) {

        }
    }
}
